package com.zhongzhi.javafx.controller;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.ResourceBundle;

import org.apache.ibatis.javassist.expr.NewArray;

import com.zhongzhi.common.Common;
import com.zhongzhi.common.CommonUpdata;
import com.zhongzhi.springboot.pojo.Measure;
import com.zhongzhi.springboot.pojo.Equipment;
import com.zhongzhi.springboot.pojo.MeasureShow;
import com.zhongzhi.springboot.pojo.MeasureTabShow;
import com.zhongzhi.springboot.pojo.StationShow;
import com.zhongzhi.springboot.pojo.Type;
import com.zhongzhi.util.ClientUtil;
import com.zhongzhi.util.JsonResult;
import com.zhongzhi.util.PageUtil;

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.DatePicker;
import javafx.scene.control.MenuButton;
import javafx.scene.control.MenuItem;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.layout.HBox;
import javafx.stage.DirectoryChooser;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.Window;
import javafx.util.Callback;
import lombok.extern.log4j.Log4j;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.image.Image;
import javafx.scene.control.TableView;
@Log4j
public class MeasureViewController implements Initializable{
	@FXML
    private TableView TableEm;//表格
    @FXML
    private DatePicker startTime;//开始时间
    @FXML
    private DatePicker endTime;//结束时间
    @FXML
    private MenuButton station;//工位
    @FXML
    private MenuItem all;
    @FXML
    private TextField Menum;
    @FXML
    private TextField num;//机号
    @FXML
    private Button select;//查询
    @FXML
    private HBox hbox;
    @FXML
    private Button startbutton;
    @FXML
    private Button upbutton;
    @FXML
    private Button skip;
    @FXML
    private Button downbutton;
    @FXML
    private Button endbutton;
    @FXML
    private Button println;//打印

    //选中的工位信息
    private Integer stationId = null;
	private int pages = 1;			//当前页
	private int number = 50;		//当前页行数
	private int TableNums = 5;		//总记录数
	private int TablePages = 5;		//总页数
	
	@Override
	public void initialize(URL location, ResourceBundle resources) {
		log.info("历史数据窗口:开始初始化");

		//初始化查询
		station();//初始化工位查询
		
		
		TableNums = Getnum();
		TablePages = TableNums/number;
		if (TableNums%number>0) {
			TablePages++;
		}
		insert(1,number);
		num.setText("1");
		
		//首页
		startbutton.setOnAction(new EventHandler<ActionEvent>() {

			@Override
			public void handle(ActionEvent event) {
				num.setText("1");
				pages=1;
				insert(1,number);
			}
		});
		//尾页
		endbutton.setOnAction(new EventHandler<ActionEvent>() {

			@Override
			public void handle(ActionEvent event) {
				num.setText(Integer.toString(TablePages));
				pages=TablePages;
				insert(TablePages, number);
			}
		});
		//前一页
		upbutton.setOnAction(new EventHandler<ActionEvent>() {

			@Override
			public void handle(ActionEvent event) {
				if(pages>1) {
					pages--;
				}
				num.setText(Integer.toString(pages));
				insert(pages, number);
			}
		});
		//后一页
		downbutton.setOnAction(new EventHandler<ActionEvent>() {

			@Override
			public void handle(ActionEvent event) {
				if(pages<TablePages) {
					pages++;
				}
				num.setText(Integer.toString(pages));
				insert(pages, number);
			}
		});
		//跳转
		skip.setOnAction(new EventHandler<ActionEvent>() {

			@Override
			public void handle(ActionEvent event) {
				int a = pages;
				try {
					a = Integer.valueOf(num.getText());
					pages =a;
				} catch (Exception e) {
					System.out.println(e);
				}
				num.setText(Integer.toString(pages));
				insert(pages, number);
			}
		});
		//查询
		select.setOnAction(new EventHandler<ActionEvent>() {
			
			@Override
			public void handle(ActionEvent event) {
				
				TableNums = Getnum();
				TablePages = TableNums/number;
				if (TableNums%number>0) {
					TablePages++;
				}
				pages=1;
				insert(1,number);
				num.setText("1");
				
			}
		});
		//工位选择
		station.setOnAction(new EventHandler<ActionEvent>() {
			
			@Override
			public void handle(ActionEvent event) {
				station();
				
			}
		});
		//选择全部
		all.setOnAction(new EventHandler<ActionEvent>() {
			
			@Override
			public void handle(ActionEvent event) {
				station.setText("全部工位");
				stationId=null;
			}
		});
		
		println.setOnAction(new EventHandler<ActionEvent>() {
			
			@Override
			public void handle(ActionEvent event) {
				PageUtil util = new PageUtil();
				util.setPage("/fxml/function/Excel.fxml", "数据导出");
			}
		});
		log.info("历史数据窗口:初始化完成");
	}
	
	
	
	/**
	 * 开始时间转为时间戳
	 * @return
	 */
	private Long statrTimeLong() {
		LocalDate value = startTime.getValue();
		if (value==null || value.equals("")) {
			return null;
		}
		String string = value.toString();
		if (string==null || string.equals("")) {
			return null;
		}
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		try {
			return format.parse(string).getTime()-24L*60*60*1000;
		} catch (ParseException e) {
			log.error("历史数据窗口:开始时间转为时间戳失败:"+startTime.getValue());
		}
		return null;
	}
	
	/**
	 * 结束转为时间戳
	 * @return
	 */
	private Long endTimeLong() {
		LocalDate value = endTime.getValue();
		if (value==null || value.equals("")) {
			return null;
		}
		String string = value.toString();
		if (string==null || string.equals("")) {
			return null;
		}
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		try {
			return format.parse(string).getTime()+24L*60*60*1000;
		} catch (ParseException e) {
			log.error("历史数据窗口:结束时间转为时间戳失败:"+endTime.getValue());
		}
		return null;
	}
	
	/**工位查询*/
	private void station() {
		try {
			String stationString = ClientUtil.Gethttp("http://127.0.0.1:8080/station/select?pages=1&line=1000");
			log.info("历史数据窗口:执行工位数据查询:"+stationString);
			JsonResult jsonobj = ClientUtil.Jsonobj(stationString, JsonResult.class);
			log.info("历史数据窗口:执行工位查询结果:"+jsonobj);
			String string = jsonobj.getData().toString();
			List<StationShow> stationlist = ClientUtil.Jsonlist(string, StationShow.class);
			for (StationShow stationShow : stationlist) {
				MenuItem item = new MenuItem(stationShow.getStationname());
				item.setOnAction(new EventHandler<ActionEvent>() {
					
					@Override
					public void handle(ActionEvent event) {
						station.setText(stationShow.getStationname());
						stationId = stationShow.getId();
					}
				});
				this.station.getItems().add(item);
			}
		} catch (Exception e) {
			log.error("历史数据窗口:执行工位查询结果失败:"+e);
		}
		
		
	}
	
	
	//执行分页查询
	private void insert(Integer pages,Integer line) {
		try {
			String httpstring = "http://127.0.0.1:8080/measure/select?pages="+pages+"&line="+line;
			
			Long statrTimeLong = statrTimeLong();
			Long endTimeLong = endTimeLong();
			String text = Menum.getText();
			
			if (text==null||text.equals("")) {
				text=null;
			}
			if (statrTimeLong!=null) {
				httpstring=httpstring+"&startTime="+statrTimeLong;
			}
			if (endTimeLong!=null) {
				httpstring=httpstring+"&endTime="+endTimeLong;
			}
			if (stationId!=null) {
				httpstring=httpstring+"&StationId="+stationId;
			}
			if (text!=null && text.equals("")!=true) {
				httpstring=httpstring+"&str="+text;
			}
			log.info("历史数据窗口:执行历史数据查询:"+httpstring);
			String gethttp = ClientUtil.Gethttp(httpstring);
			log.info("历史数据窗口:执行历史数据查询结果:"+gethttp);
			JsonResult jsonobj = ClientUtil.Jsonobj(gethttp, JsonResult.class);
			String string = jsonobj.getData().toString();
			List<MeasureShow> jsonlist = ClientUtil.Jsonlist(string, MeasureShow.class);
			if (jsonlist!=null) {
				List<MeasureTabShow> shouToTabShow = shouToTabShow(jsonlist);
				TableShow(TableEm,shouToTabShow);
				tabAddButton();
			}
		} catch (Exception e) {
			log.error("历史数据窗口:执行历史数据查询结果失败:"+e);
		}
		
		
	}

	//查询总记录数
	private int Getnum() {
		
		try {
			String httpstring = "http://127.0.0.1:8080/measure/selectSize";
			
			Long statrTimeLong = statrTimeLong();
			Long endTimeLong = endTimeLong();
			String text = Menum.getText();
			if (text==null||text.equals("")) {
				text=null;
			}
			if (statrTimeLong!=null) {
				httpstring=httpstring+"?startTime="+statrTimeLong;
			}else {
				httpstring=httpstring+"?startTime=0";
			}
			if (endTimeLong!=null) {
				httpstring=httpstring+"&endTime="+endTimeLong;
			}
			if (stationId!=null) {
				httpstring=httpstring+"&StationId="+stationId;
			}
			if (text!=null && text.equals("")!=true) {
				httpstring=httpstring+"&str="+text;
			}
			
			log.info("历史数据窗口:执行记录总数查询:"+httpstring);
			String gethttp = ClientUtil.Gethttp(httpstring);
			log.info("历史数据窗口:执行记录总数查询结果:"+gethttp);
			JsonResult jsonobj = ClientUtil.Jsonobj(gethttp, JsonResult.class);
			return (int) jsonobj.getData();
		} catch (Exception e) {
			log.error("历史数据窗口:执行记录总数查询结果失败:"+e);
			return 0;
		}
		
	}

	//将MeasureShow转为MeasureTabShow
	private List<MeasureTabShow> shouToTabShow(List<MeasureShow> list){
		List<MeasureTabShow> tableView = new ArrayList<MeasureTabShow>();
		for (MeasureShow measureShow : list) {
			MeasureTabShow show = new MeasureTabShow(measureShow);
			tableView.add(show);
		}
		return tableView;
	}
	
	//将查询结果加入表格
	private void TableShow(TableView<MeasureTabShow> tab,List<MeasureTabShow> list) {
		tab.getColumns().clear();
		TableColumn id = new TableColumn("ID");
		id.setCellValueFactory(new PropertyValueFactory("id"));
		
		TableColumn<MeasureTabShow,String> deviceNum = new TableColumn<MeasureTabShow,String>("机号");
		deviceNum.setCellValueFactory(new PropertyValueFactory("deviceNum"));
		
		TableColumn typeName = new TableColumn("机型");
		typeName.setCellValueFactory(new PropertyValueFactory<>("typeName"));
		
		TableColumn startTime = new TableColumn("开始时间");
		startTime.setCellValueFactory(new PropertyValueFactory<>("startTime"));
		
		TableColumn endTime = new TableColumn("结束时间");
		endTime.setCellValueFactory(new PropertyValueFactory<>("endTime"));
		
		TableColumn stationName = new TableColumn("工位");
		stationName.setCellValueFactory(new PropertyValueFactory<>("stationName"));
		
		TableColumn sinkA = new TableColumn("下沉量a");
		sinkA.setCellValueFactory(new PropertyValueFactory<>("sinkA"));
		
		TableColumn startAltitudeA = new TableColumn("初始高度a");
		startAltitudeA.setCellValueFactory(new PropertyValueFactory<>("startAltitudeA"));
		
		TableColumn sinkB = new TableColumn("下沉量b");
		sinkB.setCellValueFactory(new PropertyValueFactory<>("sinkB"));
		
		TableColumn startAltitudeB = new TableColumn("初始高度b");
		startAltitudeB.setCellValueFactory(new PropertyValueFactory<>("startAltitudeB"));
		
		TableColumn remark = new TableColumn("备注信息");
		remark.setCellValueFactory(new PropertyValueFactory<>("remarks"));
		
		TableColumn ceshia = new TableColumn("测试点a数据");
		ceshia.getColumns().addAll(sinkA,startAltitudeA);
		
		TableColumn ceshib = new TableColumn("测试点b数据");
		ceshib.getColumns().addAll(sinkB,startAltitudeB);
		ObservableList<MeasureTabShow> data = FXCollections.observableArrayList();
		tab.setItems(data);
		tab.getColumns().addAll(id,deviceNum,typeName,startTime,endTime,stationName,ceshia,ceshib,remark);
		if (list!=null) {
			for (MeasureTabShow measureShow : list) {
				data.add(measureShow);
			}
		}
	}
	
	//为tab增加按钮
	private void tabAddButton() {
		
		TableColumn<MeasureTabShow, Void> delete = new TableColumn<MeasureTabShow, Void>("删除");
		Callback<TableColumn<MeasureTabShow, Void>, TableCell<MeasureTabShow, Void>> callback2 = new Callback<TableColumn<MeasureTabShow,Void>, TableCell<MeasureTabShow,Void>>() {
			@Override
			public TableCell<MeasureTabShow, Void> call(TableColumn<MeasureTabShow, Void> arg0) {
				TableCell<MeasureTabShow, Void> cell = new TableCell<MeasureTabShow, Void>(){
					Button button =  new Button("删除");
					{
						button.setOnAction(new EventHandler<ActionEvent>() {

							@Override
							public void handle(ActionEvent arg0) {
								MeasureTabShow MeasureTabShow = getTableView().getItems().get(getIndex());
								String s = "http://127.0.0.1:8080/measure/delete?id="+MeasureTabShow.getId();
								ClientUtil.Gethttp(s);
								insert(TablePages, number);
							}
						});
					}
					@Override
					protected void updateItem(Void item, boolean empty) {
						super.updateItem(item, empty);
						if (empty) {
							setGraphic(null);
						} else {
							setGraphic(button);
						}
					}
				};
				return cell;
			}
		};
		
		delete.setCellFactory(callback2);
		TableEm.getColumns().add(delete);
	}

}
